/*
 * @Description: 公共函数
 * @Date: 2018-12-29 11:20:13
 */
//import {JSEncrypt} from 'jsencrypt'
import { UpdateStatus } from './redux' // RSA  JSEncrypt加密
import axios from '../rudexRou/urlHttp.js'
const { JSEncrypt } = require('encryptlong')
export function setCookie(name, value) {
  //写cookies，一个小时过期
  var exp = new Date()
  exp.setTime(exp.getTime() + 60 * 60 * 1000 * 24 * 3)
  document.cookie =
    name + '=' + escape(value) + ';expires=' + exp.toGMTString() + ';path=/'
}
export function getCookie(name) {
  //读取cookies \
  var arr,
    reg = new RegExp('(^| )' + name + '=([^;]*)(;|$)')
  if ((arr = document.cookie.match(reg))) return unescape(arr[2])
  else return null
}
export function delCookie(name) {
  //删除cookies
  var exp = new Date()
  exp.setTime(exp.getTime() - 30 * 60 * 1000 * 24 * 3)
  var cval = getCookie(name)
  if (cval != null)
    document.cookie =
      name + '=' + cval + ';expires=' + exp.toGMTString() + ';path=/'
}
// 处理session过期跳转登录操作
export function VerifySessionTime(objs) {
  objs.props.history.push({ pathname: '/login', state: '' })
}
//环境设置（用于区分是开发环境还是打包环境）
export function devProTest() {
  // return '24'
  return 'ipsa'
  // return 'ipsa-test'
  // return 'develop'
}
export function getAjaxurl() {
  //删除cookies
  let urls = 'http://10.61.121.178:8080/iCan/bk'
  if (devProTest() === '24' || devProTest() === 'ipsa') {
    // 24 服务器
    urls = window.location.origin + '/iCan/bk'
  } else if (devProTest() === 'ipsa-test') {
    urls = window.location.origin + '/iCan_Test/bk'
  } else if (devProTest() === 'develop') {
    // urls = 'http://10.61.121.24:8080/iCan/bk'
    //  urls = 'http://ipsapro.isoftstone.com/iCan/bk';
    // urls = 'http://10.61.121.79:8762'
    // urls = 'http://10.61.121.79:8080/iCan/bk/'
    // urls = 'http://10.61.121.178:8103'
    // urls = 'http://10.61.121.13:8103'
    // urls="http://10.60.95.254:8103"
    // urls = 'http://ipsapro.isoftstone.com/iCan_Test/bk';
    // urls = 'http://ipsapro.isoftstone.com/iCan/bk';
    urls = '/'
  }
  return urls
}
//前端访问ip （用于开发环境，打包环境忽略）
export function frontUrlTest() {
  //  return 'http://10.61.121.30'
  return window.location.origin
  //return 'http://10.61.121.69'
}
// 请求链接
export function getResponseUrl(mark) {
  switch (mark) {
    case 'ResponsePMITSystem': // 登录PMIT并且  获取信息安全需要的PMIT数据
      return (
        window.location.protocol + '//ipsapro.isoftstone.com/MAG_PMIT/new/bk'
      )
    case 'SafeSystem': // 信息安全
      // 线上后台地址
      return (
        window.location.protocol + '//ipsapro.isoftstone.com/MAG_SMARTSAFE/MS'
      )
    case 'login_MAG_iHMS': // 黄区申请
      return window.location.protocol + '//ipsapro.isoftstone.com'
    case 'TotalCost': //Wip
      if (devProTest() === '24' || devProTest() === 'ipsa') {
        return window.location.origin + '/iCan/bk/cost'
      } else if (devProTest() === 'ipsa-test') {
        return window.location.origin + '/iCan_Test/bk/cost'
      } else if (devProTest() === 'develop') {
        return 'http://10.61.121.77:8103/cost'
        // return 'http://ipsapro.isoftstone.com/iCan/bk/cost';
        // return 'http://ipsapro.isoftstone.com/iCan_Test/bk/cost';
      }
  }
}
// 跳转链接
export function getLinkToUrl(mark) {
  let urls = ''
  console.log('mark========================', mark)
  switch (mark) {
    case 'Home': // 跳至主页
      switch (devProTest()) {
        case 'ipsa-test':
          return (urls = window.location.origin + '/iCan_Test/#/MAG-ICAN')
          break
        case 'develop':
          return (urls = frontUrlTest() + ':5002/#/MAG-ICAN')
          break
        default:
          return (urls = window.location.origin + '/iCan/#/MAG-ICAN')
          break
      }
      break
    case 'iCanLogin':
      switch (devProTest()) {
        case 'develop':
          return (urls = frontUrlTest() + ':5008/#/login')
          break
        case 'ipsa-test':
          return (urls = window.location.origin + '/iCan_Test/#/login')
          break
        default:
          return (urls = window.location.origin + '/iCan/#/login')
          break
      }
      break
    case 'platform': // 查看页面
      switch (devProTest()) {
        case 'ipsa-test':
          return (urls = window.location.origin + '/iCan_Test')
          break
        case 'develop':
          return (urls = frontUrlTest())
          break
        default:
          return (urls = window.location.origin + '/iCan')
          break
      }
      break
    case 'ipsa': // 查看页面
      return (urls = 'http://ipsapro.isoftstone.com')
      break
  }
}

// RSA  JSEncrypt加密公钥，后台有对应私钥解密
export function compileStr(code) {
  //对字符串进行加密
  let publicKey =
    'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDCd2gBVuBQoz2bumFjo+h1+EvMt5qGiysTh1oTlL' +
    'F4EujAhJF8yk4HmlD/sYXrs9Zbci9xuvHCRZQTQrkv9KzsrLV70EMHmtq5SbKKcYQKIwDVcc9tyCsIpqrvtotRtN1Y7mmL0' +
    'K6pquSNpmnMgMV75MpOqdfW23gH9rloHLOOIwIDAQAB'
  let encryptor = new JSEncrypt()
  encryptor.setPublicKey(publicKey)
  let a = encryptor.encryptLong(code)
  return a
}

//字符串进行解密     RSA  JSEncrypt解密密码
export function uncompileStr(code) {
  let PRIVATE_KEY =
    'MIICdQIBADANBgkqhkiG9w0BAQEFAASCAl8wggJbAgEAAoGBAMJ3aAFW4FCjPZu6YWOj6HX4S8y3m' +
    'oaLKxOHWhOUsXgS6MCEkXzKTgeaUP+xheuz1ltyL3G68cJFlBNCuS/0rOystXvQQwea2rlJsopxhAojANVxz23IKwimqu+2i1G03V' +
    'juaYvQrqmq5I2macyAxXvkyk6p19bbeAf2uWgcs44jAgMBAAECgYBFG54Qa8lHntt0DiYx/LvNwLFfTRhTG/3w8LboIn13CHFCiVoSm' +
    'Opl9Uc3tuS6wKw6zzdhGWh0+7kFpz6cdj1FN1Zhjp2wOwQdGcD0TBW3iMcGpLdmTzzFufxUT3uKpCnkRwECnNWi7AcYozAgTt5DM8xZ47A' +
    'k1C8yKMigyIupsQJBAPROmm2WuHUO7v9Pzp7oMn9Kq8qbjkiWRg1DS2t6aVCwgNCV+k2udY9ZpqWsHSNHj83BlVuT/5MX1rO5koNIEJUCQQD' +
    'LxiA50E8j0FFLOG+/araG0aBvDkqpbRdLRjOKfZgADjzyIXX3xn/B07R7NCN+e63afvSeBX1SZmj39dvJKd3XAkBOcn77+Y25aNYtfT7nn7+' +
    '3SA7pvBFwFXDhCV7KYEA4/LQgRkhdcUumgC8Wu7GPhocSlrqS8W77mIgEpe354cYRAkA15LefMsXLjgwCHfIIKTwPGiAZXylF+BFCGlYFWcQ6' +
    't4lM7Kabmocth0VjlF2S1Tkc4ZjmtkL36Rf4BLFVWdpPAkBwX4zhGSAVwaPIVsgHgCSJ3XqPQ7EnfplsZn2DthVTwDYeoMNcalGVJhp4ioltESD' +
    'ev53J9j/kDt7T+HUECVGu'
  let decryptor = new JSEncrypt() // 新建JSEncrypt对象
  decryptor.setPrivateKey(PRIVATE_KEY) // 设置私钥
  return decryptor.decrypt(code)
}
export function compileStrCop(code) {
  //对字符串进行加密
  let publicKey =
    'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCCbGIoHOdltxr6eg9oQf+fL1+pQ+IhT6GrP9W4jfStg9mZpqxUI2fAEbUf1WDK9YRDGMwGta5GI6faF4vOuUOsFbuAuJb+BD8vxISmVyByS3mqIq44rP52H+U73wyfpLRhc7QuG0ibKngdnTeNEI5TKXxt8HIj2sAZRcJR34f5mQIDAQAB'
  let encryptor = new JSEncrypt()
  encryptor.setPublicKey(publicKey)
  let a = encryptor.encryptLong(code)
  return a
}
// 获取字典信息并分类筛选
export function DictionaryTypeList(e) {
  let arr = UpdateStatus().DictionaryInfo.DictionaryInfo
  let a = arr.filter((val, index) => {
    return val.typeCnName === e
  })
  return a
}

// 字典数据回显
export function getDictionaryLabel(type, code) {
  if (!code) {
    code = 'def'
  }
  if (type) {
    let arr = JSON.parse(localStorage.getItem('dictionary'))
    if (arr) {
      let item = arr.find((val) => {
        return val.code == type
      })
      if (item) {
        if (code !== 'def') {
          const option = item.values.find((obj) => obj.code.trim() == code)
          return option ? option.label : ''
        } else {
          return item.values
        }
      } else {
        return []
      }
    } else {
      return null
    }
  } else {
    return ''
  }
}

// 字典数据回显
export function getRegionLableLabel(type, code) {
  const regionList = sessionStorage.getItem('regionList')
    ? JSON.parse(sessionStorage.getItem('regionList'))
    : []
  console.log('regionList:', regionList)
  if (regionList && regionList.length > 0) {
    const addressList = getDictionaryLabel(type, code)
    return addressList.filter((item) => {
      return regionList.indexOf(item.code) > -1
    })
  } else {
    return getDictionaryLabel(type, code)
  }
}
//获取当前时间
export function getTime() {
  let myDate = new Date()
  let DateString = myDate.toLocaleDateString()
  DateString = DateString.replace('/', '-').replace('/', '-')
  return DateString
}

export function isEqual(a, b) {
  //如果a和b本来就全等
  if (a === b) {
    //判断是否为0和-0
    return a !== 0 || 1 / a === 1 / b
  }
  //判断是否为null和undefined
  if (a == null || b == null) {
    return a === b
  }
  //接下来判断a和b的数据类型
  var classNameA = toString.call(a),
    classNameB = toString.call(b)
  //如果数据类型不相等，则返回false
  if (classNameA !== classNameB) {
    return false
  }
  //如果数据类型相等，再根据不同数据类型分别判断
  switch (classNameA) {
    case '[object RegExp]':
    case '[object String]':
      //进行字符串转换比较
      return '' + a === '' + b
    case '[object Number]':
      //进行数字转换比较,判断是否为NaN
      if (+a !== +a) {
        return +b !== +b
      }
      //判断是否为0或-0
      return +a === 0 ? 1 / +a === 1 / b : +a === +b
    case '[object Date]':
    case '[object Boolean]':
      return +a === +b
  }
  //如果是对象类型
  if (classNameA === '[object Object]') {
    //获取a和b的属性长度
    var propsA = Object.getOwnPropertyNames(a),
      propsB = Object.getOwnPropertyNames(b)
    if (propsA.length !== propsB.length) {
      return false
    }
    for (var i = 0; i < propsA.length; i++) {
      var propName = propsA[i]
      //如果对应属性对应值不相等，则返回false
      if (a[propName] !== b[propName]) {
        return false
      }
    }
    return true
  }
  //如果是数组类型
  if (classNameA === '[object Array]') {
    if (a.toString() === b.toString()) {
      return true
    }
    return false
  }
}

export function IsEmailFormat(value) {
  // let reg = /^([a-zA-Z]|[0-9]|[_|\_|\.])(\w|\-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/
  let reg = /^([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/
  return reg.test(value)
}
function getAxios(url) {
  return new Promise((resolve, reject) => {
    axios
      .get(url)
      .then((response) => {
        resolve(response)
      })
      .catch((err) => {
        reject(err)
      })
  })
}

//从操作权限数组查看是否有权限
export function queryAuth(key, list) {
  let isRight = false
  if (list && list.length > 0) {
    list.filter((item) => {
      if (item.interceptor && item.interceptor.includes(key)) {
        isRight = true
      }
    })
    return isRight
  }
}

//menuId：菜单Id 使用场景 根据url参数menuId 找对应的 子集或者资源项
//parentId：父Id 使用场景，根据url参数parentId 找对应 子集  如果为 -1 则用menuId找
export function findConfig(config, menuId, parentId) {
  let isContinue = true //退出循环标记（为false 时，不在进入循环）
  sonMenusDatas = []
  let arry = JSON.parse(config)
  let sonMenus = []
  for (var i = 0; i < arry.length && isContinue; i++) {
    if (arry[i].systemId === menuId && arry[i].services.length > 0) {
      isContinue = false
      sonMenus = arry[i].services //  找到体系下services所有自己 找到即停止循环
      return sonMenus
    } else {
      for (var j = 0; j < arry[i].services.length && isContinue; j++) {
        if (arry[i].services[j].menuId == menuId) {
          if (parentId && parentId == -1) {
            sonMenus = [{ ...arry[i].services[j] }] //找到services中某一个，找到即停止循环
          } else {
            sonMenus = arry[i].services[j].sonMenus
          }
          isContinue = false //找到子集，即更改
          //  break
          return sonMenus
        } else {
          sonMenus = getSonMenus(arry[i].services[j], menuId, isContinue) //菜单递归处理
          if (sonMenus && sonMenus.length > 0) {
            isContinue = false
            return sonMenus
          }
        }
      }
    }
  }
}
let sonMenusDatas = [] //所有找到子菜单数据集合
function getSonMenus(val, menuId, isContinue) {
  let isAllow = isContinue
  for (var i = 0; i < val.sonMenus.length && isAllow; i++) {
    if (val.sonMenus[i].sonMenus) {
      if (val.sonMenus[i].menuId == menuId) {
        isAllow = false
        sonMenusDatas = val.sonMenus[i].sonMenus
        break
      }
      if (
        val.sonMenus[i].sonMenus.length > 0 &&
        isAllow &&
        val.sonMenus[i].type != 2
      ) {
        getSonMenus(val.sonMenus[i], menuId, isAllow)
      }
    } else {
      continue
    }
  }
  return sonMenusDatas
}
export function getHeaderParams() {
  let pathname = window.location.href
  let pathObj = {}
  let pos = ''
  pathname = pathname.split('&')
  pathname.shift(0)
  pathname.forEach((path) => {
    pos = path.indexOf('=')
    pathObj[path.substring(0, pos)] = path.substring(pos + 1)
  })
  return pathObj
}
